<template>
  <div class="distribute-detail">
    <n-card v-if="loading" :bordered="false" class="proCard">
      <n-spin :show="loading" class="loading" />
    </n-card>

    <DFPageDetail v-else ref="dfPageDetailRef" :pageOptions="pageOptions" />

    <ComputedDialog
      ref="computedDialogRef"
      :orderKeyList="orderKeyList"
      @setRowFormulaListFn="setRowFormulaListFn"
    />
  </div>
</template>

<script lang="ts" setup name="DistributeDetail">
  import lang from '../lang';

  import { useMixins } from '@/hooks/useMixins';

  import { addDistribute, updateDistribute, infoDistribute } from '@/api/gather/distribute';

  import { distributeTypeList, isSaveByMaterialList, typeList } from './data';

  import { listMachine } from '@/api/base/machine';
  import { listGatherParameter } from '@render/api/gather/parameter';
  import { cloumsMaterial } from '@render/api/base/material';

  import ComputedDialog from './ComputedDialog.vue';
  import { cloumsOrder } from '@render/api/production/order';

  import { renderSvg } from '@/utils/index';

  import Sortable from 'sortablejs';

  const { t, loadLangFn, routerType, message } = useMixins();

  const loading = ref(false);

  const machineList = ref([]);

  const gatherParameterList = ref([]);

  const orderKeyList = ref([]);

  const computedDialogRef = ref();

  const dfPageDetailRef = ref();

  const list = ref();

  let formulaListRow = null;

  loadLangFn(lang);

  const initFn = async () => {
    try {
      loading.value = true;

      const res = await Promise.all([
        listMachine(),
        listGatherParameter(),
        cloumsOrder(),
        cloumsMaterial(),
      ]);

      const [list1, list2, list3, list4] = res;

      machineList.value =
        list1?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

      gatherParameterList.value =
        list2?.data.map((item) => ({
          label: item.parameterName,
          value: item.parameterName,
          parameterCode: item.parameterCode,
        })) || [];

      orderKeyList.value =
        [...list3?.data, ...list4.data]
          .filter(
            (item) =>
              ![
                'createUserName',
                'createName',
                'createTime',
                'updateUserName',
                'updateName',
                'updateTime',
                'id',
                'remark',
                'customCode',
                'orderStatusCode',
                'materialRemark',
                'adjuestNum',
                'producedNum',
                'adjuestSuccessTime',
              ].includes(item.key)
          )
          .map((item) => ({
            label: t(`distribute.table.${item.key}`),
            value: item.key,
          })) || [];
    } catch (e) {
      console.log(e);
    }

    loading.value = false;

    setTimeout(() => {
      nextTick(async () => {
        // 需要支持拖动效果的列表容器，在这里我们设置为el-table组件的tbody，
        // 注意：最前面的一段为前面el-table的class: draggable-table，主要为了防止如果页面有多个table，多个table同时实现拖拽效果
        // 当然，如果多个table都需要拖拽效果，选择器中最前面的.draggable-table可以去除。

        if (
          dfPageDetailRef &&
          dfPageDetailRef.value &&
          dfPageDetailRef.value.getDetailRefListDataFn
        ) {
          const data = await dfPageDetailRef.value.getDetailRefListDataFn();

          const { distributeList = [] } = data;

          list.value = distributeList || [];

          const tbody = document.querySelector('.distribute-detail .n-data-table-tbody');

          new Sortable(tbody, {
            animation: 150,
            handle: '.fixed-modal-sort',
            filter: '.no-draggable',
            invertSwap: false,
            preventOnFilter: true,
            onSort(/** Event */ _evt) {
              // console.log('sort',evt)
              // 与 onEnd 相同的属性
            },
            onChange(_e, _a, _c) {
              // console.log('change',e)
              // console.log(a)
              // if(e.newIndex === 2){
              //   return false
              // }
            },
            onMove(/** Event */ _evt, /** Event */ _originalEvent) {
              // console.log('move',evt)
              // console.log(originalEvent)
              // if(evt.newIndex === 2){
              //   return false
              // }
              // return false
            },
            // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
            onEnd: ({ newIndex, oldIndex }) => {
              // console.log(newIndex)

              // console.log(oldIndex)

              const targetRow = list.value[oldIndex];
              list.value.splice(oldIndex, 1);
              list.value.splice(newIndex, 0, targetRow);

              list.value.forEach((item, key) => {
                item.index = key + 1;
              });

              dfPageDetailRef.value.setEditTableAllDataFn('distributeList', list);

              // console.table(this.dialogTableDataList);
            },
          });
        }
      });
    }, 500);
  };

  const pageOptions = {
    list: [
      {
        type: 'form',
        formSchemas: [
          {
            label: 'machineName',
            prop: 'machineCode',
            component: 'NSelect',
            options: machineList,
            required: true,
          },
          {
            label: 'remark',
            type: 'textarea',
            common: true,
            giProps: { span: 3 },
            componentProps: {
              'show-count': true,
            },
          },
        ],
      },
      {
        title: t('distribute.table.tableName'),
        type: 'table',
        hasSelection: true,
        ref: 'distributeList',
        pagination: false,
        columns: [
          {
            label: 'sort',
            common: true,
            sorter: false,
            align: 'center',
            fixed: 'right',
            className: 'sort-column',
            // title() {
            //   return h('div', {
            //     class: '123123123',
            //     width: '100%',
            //     'text-align': 'center',
            //     innerText: t(`common.table.sort`),
            //   });
            // },
            render(_row) {
              return h(renderSvg('fixedModalSort'), { class: 'fixed-modal-sort' });
            },
          },
          {
            label: 'parameterName',
            prop: 'parameterName',
            required: true,
            itemData: {
              component: 'NSelect',
              options: gatherParameterList,
              componentProps: {
                onUpdateValue(_v: string, option: any, updateFormModelFn: any, row: any) {
                  if (row && option) {
                    const { value = null, parameterCode = null } = option;

                    const data: any = {
                      parameterName: value,
                      parameterCode,
                    };

                    typeof updateFormModelFn === 'function' && updateFormModelFn(data);
                  } else {
                    typeof updateFormModelFn === 'function' &&
                      updateFormModelFn({
                        parameterName: null,
                        parameterCode: null,
                      });
                  }
                },
              },
            },
          },
          {
            label: 'parameterCode',
          },
          {
            label: 'type',
            required: true,
            itemData: {
              defaultValue: 'value',
              component: 'NSelect',
              options: typeList,
            },
          },
          {
            label: 'value',
            itemData: {
              component: 'NInputNumber',
              maxlength: 4,
              precision: 0,
              max: 9999,
              min: 0,
            },
          },
          {
            label: 'orderKey',
            itemData: {
              component: 'NSelect',
              options: orderKeyList,
            },
          },
          {
            label: 'formulaList',
            render: (row) => {
              return h('span', {
                innerText: t('common.button.edit'),
                class: 'df-table-button',
                onClick: () => {
                  if (computedDialogRef && computedDialogRef.value) {
                    computedDialogRef.value.openModalFn(toRaw(row.formulaList) || []);

                    formulaListRow = row;
                  } else {
                    formulaListRow = null;
                  }
                },
              });
            },
          },
          {
            label: 'decimalPlaces',
            required: true,
            itemData: {
              defaultValue: 0,
              component: 'NInputNumber',
              maxlength: 4,
              precision: 0,
              max: 9999,
              min: 0,
            },
          },
          {
            label: 'isSaveByMaterial',
            required: true,
            itemData: {
              defaultValue: 1,
              component: 'NSelect',
              options: isSaveByMaterialList,
            },
          },
          {
            label: 'saveParameterName',
            prop: 'saveParameterName',
            itemData: {
              component: 'NSelect',
              options: gatherParameterList,
              componentProps: {
                onUpdateValue(_v: string, option: any, updateFormModelFn: any, row: any) {
                  if (row && option) {
                    const { value = null, parameterCode = null } = option;

                    const data: any = {
                      saveParameterName: value,
                      saveParameterCode: parameterCode,
                    };

                    typeof updateFormModelFn === 'function' && updateFormModelFn(data);
                  } else {
                    typeof updateFormModelFn === 'function' &&
                      updateFormModelFn({
                        saveParameterName: null,
                        saveParameterCode: null,
                      });
                  }
                },
              },
            },
          },
          {
            label: 'saveParameterCode',
          },
          {
            label: 'distributeType',
            required: true,
            itemData: {
              defaultValue: 1,
              component: 'NSelect',
              options: distributeTypeList,
            },
          },
          {
            label: 'delayTime',
            required: true,
            itemData: {
              defaultValue: 1000,
              component: 'NInputNumber',
              maxlength: 5,
              precision: 0,
              max: 99999,
              min: 0,
            },
          },
          {
            label: 'isDistributeByAutoChangeOrder',
            required: true,
            itemData: {
              defaultValue: 0,
              component: 'NSelect',
              options: isSaveByMaterialList,
            },
          },
          {
            label: 'remark',
            common: true,
            itemData: {
              maxlength: 100,
            },
          },
        ],
      },
    ],
    formLabelWidthEn: 100,
    descriptionsListLabelWidthEn: 150,
    routeName: 'distribute',
    addDataFn: addDistribute,
    updateDataFn: updateDistribute,
    getDataFn: infoDistribute,
    handleEditDataFn: (res) => {
      const { data } = res;

      if (routerType === 'copy') {
        delete data.id;

        if (data.distributeList && data.distributeList.length) {
          for (const item of data.distributeList) {
            const { formulaList } = item;

            if (formulaList && formulaList.length) {
              for (const fItem of formulaList) {
                delete fItem.id;
              }
            }

            delete item.id;
          }
        }
      }

      return data;
    },
    beforeSubmitFn: (res) => {
      const { distributeList = [], machineCode } = res;

      if (distributeList && distributeList.length) {
        const isSubmit = distributeList.every((item, index) => {
          const { type, value, formulaList, parameterCode, parameterName, orderKey } = item;

          if (type === 'value') {
            if (!value && value !== 0) {
              message.error(t('distribute.tipMsg.valueErr').replace('$index', index + 1));

              return false;
            }
          } else if (type === 'orderKeyValue' || type === 'orderKeyComputedValue') {
            if (!orderKey) {
              message.error(t('distribute.tipMsg.orderKeyErr').replace('$index', index + 1));

              return false;
            }
          } else if (type === 'computedValue' || type === 'orderKeyComputedValue') {
            if (!formulaList || formulaList.length === 0) {
              message.error(t('distribute.tipMsg.formulaListErr').replace('$index', index + 1));

              return false;
            }
          }

          item.machineCode = machineCode;

          item.proOrder = index;

          let hasOrderKeyValue = false;

          if (formulaList && formulaList.length) {
            for (const fItem of formulaList) {
              if (hasOrderKeyValue === false && fItem.orderKeyValue) {
                hasOrderKeyValue = true;
              }

              fItem.machineCode = machineCode;

              fItem.parameterCode = parameterCode;

              fItem.parameterName = parameterName;
            }
          }

          if (type === 'orderKeyComputedValue' && !hasOrderKeyValue) {
            message.error(t('distribute.tipMsg.hasOrderKeyValueErr').replace('$index', index + 1));

            return false;
          }

          return true;
        });

        return isSubmit;
      }

      return true;
    },
  };

  const setRowFormulaListFn = (list) => {
    if (formulaListRow) {
      formulaListRow.formulaList = list;
    }

    // if (dfPageDetailRef && dfPageDetailRef.value && dfPageDetailRef.value.setEditTableAllDataFn) {
    //   dfPageDetailRef.value.setEditTableAllDataFn('distributeList', list);
    // }
  };

  initFn();
</script>

<style lang="less" scoped>
  .distribute-detail {
    position: relative;
    .loading {
      width: 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
</style>

<style lang="less">
  .distribute-detail {
    .fixed-modal-sort {
      width: 18px;
      height: 18px;
      margin: 0 auto;
      cursor: move;
    }
  }
  .sort-column > .n-data-table-th__title-wrapper {
    justify-content: space-around;
  }
</style>
